package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.DictConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Message;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.MessageService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.*;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.util.common;
import com.ibeetl.cms.web.quer3.RentingExamineQuery;
import com.ibeetl.cms.web.query.RentingQuery;
import com.ibeetl.cms.web.query2.RentingEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 租房补贴 接口
 */
@Controller
public class RentingController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/renting";


    @Autowired private RentingService rentingService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired private EnterpriseService enterpriseService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired
    private  SincerityService sincerityService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private RelativesService relativesService;

    @Autowired
    private DictConsoleService dictConsoleService;

    @Autowired
    private PretrialService pretrialService;

    @Autowired
    private DeclareLimitService declareLimitService;

    private StateTable stateTable=new StateTable();

    /**
     ** 功能描述:申报、受理、初审、复审
     *  待审数据-页面请求
     ** @author liujun
     ** @date 2020/1/3 14:40
     **/
    @GetMapping(MODEL + "/index.do")
    @ResponseBody
    public ModelAndView index(String roleName,String year,String entName) {
        ModelAndView view;
        if (roleName.equals("shenbao")) {
            view = new ModelAndView("/cms/renting/index.html") ;
            view.addObject("search",RentingQuery.class.getName());
        } else if (roleName.equals("shouli")) {
            view = new ModelAndView("/cms/renting/enterpriseindex.html");
            view.addObject("search",RentingEnterpriseQuery.class.getName());
        } else if (roleName.equals("chushen")) {
            view = new ModelAndView("/cms/renting/chushenindex.html");
            view.addObject("search", RentingExamineQuery.class.getName());
        } else {
            view = new ModelAndView("/cms/renting/fushenindex.html");
            view.addObject("search",RentingExamineQuery.class.getName());
        }

        if (roleName.equals("chushen") || roleName.equals("fushen")) {
            RentingQuery condtion = new RentingQuery();
            if(StringUtils.isNotEmpty(entName)){
                condtion.setEnterprisName(entName.trim());
            }
            view.addObject("entName",entName);
            if(StringUtils.isEmpty(year)){
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            view.addObject("year",year);
            condtion.setYear(year);

            /**
             * 获取本年度所有有申报的公司
             */
            List<Renting> lists = rentingService.queryCompany(condtion);
            List<Map<String, Object>> companies = new ArrayList<>(16);

            for (Renting renting : lists) {
                if(renting.getCompanyId() == null){
                    continue;
                }
                Map<String, Object> item = new HashMap<>(8);
                int  waitCheckNumber = 0;
                int  allCheckNumber = 0;
                if (roleName.equals("chushen")) {
                    waitCheckNumber = firstCheckNumber(Long.valueOf(renting.getCompanyId()), "TODO",year);
                    allCheckNumber = firstCheckNumber(Long.valueOf(renting.getCompanyId()), "ALL",year);
                }else{
                    waitCheckNumber = finalCheckNumber(Long.valueOf(renting.getCompanyId()), "TODO",year);
                    allCheckNumber = finalCheckNumber(Long.valueOf(renting.getCompanyId()), "ALL",year);
                }
                if(waitCheckNumber == 0){
                    //无待审核记录 不展示企业
                    continue;
                }
                item.put("companyId", renting.getCompanyId());
                item.put("companyName", renting.getCurrentWorkingEnterprise());
                item.put("waitCheckNumber", waitCheckNumber);
                item.put("allCheckNumber", allCheckNumber);
                companies.add(item);
            }
            view.addObject("companies", companies);

            view.addObject("roleName", roleName);
        }
        return view;
    }

    /**
     * 获得本年度已办任务
     */
    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(RentingQuery condtion) {
        if(StringUtils.isEmpty(condtion.getYear())){
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            String yearStr = year.toString();
            condtion.setYear(yearStr);
        }

        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.renting);
        PageQuery page = condtion.getPageQuery();
        rentingService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 初审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/employees.json")
    @Function("renting.check")
    @ResponseBody
    public JsonResult<PageQuery> employees(String companyId,String year) {
        RentingQuery condtion = new RentingQuery();

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);
        condtion.setCompanyId(companyId);

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FIRSTCHECK_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        condtion.setIds(ids);

        PageQuery page = condtion.getPageQuery();
        rentingService.queryEmployees(page);
        return JsonResult.success(page);
    }

    /**
     * 复审获取该申报，该公司下的员工
     *
     * @param companyId
     * @return
     */
    @PostMapping(MODEL + "/fushenemployees.json")
    @Function("renting.review")
    @ResponseBody
    public JsonResult<PageQuery> fushenemployees(String companyId,String year) {
        RentingQuery condtion = new RentingQuery();

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condtion.setYear(year);
        condtion.setCompanyId(companyId);

        List<String> ids = new ArrayList();
        ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        condtion.setIds(ids);

        PageQuery page = condtion.getPageQuery();
        rentingService.queryEmployees(page);
        return JsonResult.success(page);
    }

    @GetMapping(MODEL + "/shenhe.do")
    @ResponseBody
    public ModelAndView shenhe(Integer id, String roleName,String bStateCode) {
        ModelAndView view;
        if(bStateCode.equals(ProcessConstant.TO_FIRSTCHECK) && roleName.equals("chushen")){
            view= new ModelAndView("/cms/renting/chushenedit.html");
        }else if(bStateCode.equals(ProcessConstant.TO_FINALCHECK)  && roleName.equals("fushen") ){
            view= new ModelAndView("/cms/renting/fushenedit.html");
        }else{
            view  = new ModelAndView("/cms/renting/findenterpriseedit.html");
            view.addObject("look",true);
        }
        List<Relatives> relatives= relativesService.findAllRelativesId(id);
        view.addObject("relatives", relatives);
        Renting renting = rentingService.queryById(id);
        renting.setRoleName(roleName);
        view.addObject("renting", renting);
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("renting")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/renting/edit.html");
        Renting renting = rentingService.queryById(id);
        List<Relatives> relatives= relativesService.findAllRelativesId(id);
        view.addObject("relatives", relatives);
        Map<Integer, String> companies = new HashMap<>(16);
        //目前已申报总月数
        int sumMonth = rentingService.findMonth(getUserId());
        //剩余可申报月数
        int subMonth = 36-sumMonth;
        if(subMonth > 12){
            subMonth = 12;
        }
        for (int i=1;i<=subMonth;i++) {
            companies.put(i, ""+i);
        }
        view.addObject("companies", companies);
        view.addObject("renting", renting);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("renting")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/renting/add.html");
        Long userId = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userId);
        view.addObject("essentialInformation", essentialInformation);
        //目前已申报总月数
        int sumMonth = rentingService.findMonth(userId);
        //剩余可申报月数
        int subMonth = 36-sumMonth;
        if(subMonth > 12){
            subMonth = 12;
        }
        view.addObject("sumMonth", subMonth);
        return view;
    }


    /**
     ** 功能描述:人才 - 个人申报记录获取
     ** @author liujun
     ** @date 2020/1/3 14:33
     **/
    @PostMapping(MODEL + "/list.json")
    @Function("renting")
    @ResponseBody
    public JsonResult<PageQuery> list(RentingQuery condtion) {
        Long userid = getUserId();
        condtion.setUserid(userid);
        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        PageQuery page = condtion.getPageQuery();
        rentingService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 受理页面数据
     * @param condtion
     * @return
     */
    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("renting.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(RentingQuery condtion) {
        Long userId = getUserId();
        condtion.setUserid(userId);
        if (StringUtils.isEmpty(condtion.getYear())) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        condtion.setCompanyId(userId.toString());
        if(StringUtils.isEmpty(condtion.getBusinessState())){
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        }else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        PageQuery page = condtion.getPageQuery();
        rentingService.findenterprise(page);
        return JsonResult.success(page);
    }

    /**
     * 新增（保存）（保存并申请）
     *
     * @param renting
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("renting")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)Renting renting,String judge,HttpServletRequest request){

        Long userId = getUserId();
        //目前已申报总月数
        int sumMonth = rentingService.findMonth(userId);
        //剩余可申报月数
        int subMonth = 36 - sumMonth;
        //当前申报数 必须小于等于剩余可申报月份数
        if(renting.getNumberDeclarations() > subMonth){
            return JsonResult.failMessage("保存失败，非法数据，本次申报月数已超过剩余可申报数！");
        }

        //获取当前申报年度参数
        String yearStr = dictConsoleService.getDeclareYear();
        renting.setYear(yearStr);
        renting.setUserId(userId.intValue());
        renting.setCompanyId(Math.toIntExact(platformService.getCurrentUser().getCompanyId()));

        common.common(stateTable,judge);
        renting.setCreationDate(new Date());
        renting.setDateReporting(stateTable.getDate());
        renting.setBusinessState(stateTable.getBusinessState());
        renting.setBusinessStateCode(stateTable.getBusinessStateCode());

        boolean success =rentingService.save(renting);
        if (success) {
            if(!renting.getMaritalStatus().equals("2")) {
                //新增亲属关系
                Relatives relatives = new Relatives();
                relatives.setRelativesId(renting.getId());

                //获取配偶信息
                String relativesName0 = request.getParameter("relativesName-0");
                String relationship0 = request.getParameter("relationship-0");
                String relativesIdType0 = request.getParameter("relativesIdType-0");
                String relativesIdNumber0 = request.getParameter("relativesIdNumber-0");
                if(StringUtils.isNotEmpty(relativesName0)){
                    relatives.setRelativesName(relativesName0);
                    relatives.setRelationship(relationship0);
                    relatives.setRelativesIdType(relativesIdType0);
                    relatives.setRelativesIdNumber(relativesIdNumber0);
                    relativesService.save(relatives);
                }

                //获取子女信息-ps:子女可能存在多个
                //姓名
                String[] relativesName = request.getParameterValues("relativesName[]");
                //关系 0-配偶 1-子女
                String[] relationship = request.getParameterValues("relationship[]");
                //证件类别
                String[] relativesIdType = request.getParameterValues("relativesIdType[]");
                //证件号码
                String[] relativesIdNumber = request.getParameterValues("relativesIdNumber[]");

                if(null == relativesName || relativesName.length == 0){
                    String relativesNameStr = request.getParameter("relativesName");
                    if(StringUtils.isNotEmpty(relativesNameStr)) {
                        String relationshipStr = request.getParameter("relationship");
                        String relativesIdTypeStr = request.getParameter("relativesIdType");
                        String relativesIdNumberStr = request.getParameter("relativesIdNumber");
                        relatives.setRelativesName(relativesNameStr);
                        relatives.setRelationship(relationshipStr);
                        relatives.setRelativesIdType(relativesIdTypeStr);
                        relatives.setRelativesIdNumber(relativesIdNumberStr);
                        relativesService.save(relatives);
                    }
                } else {
                    for (int i = 0; i < relativesName.length; i++) {
                        if(StringUtils.isNotEmpty(relativesName[i])) {
                            relatives.setRelativesName(relativesName[i]);
                            relatives.setRelationship(relationship[i]);
                            relatives.setRelativesIdType(relativesIdType[i]);
                            relatives.setRelativesIdNumber(relativesIdNumber[i]);
                            relativesService.save(relatives);
                        }
                    }
                }
            }
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),stateTable.getBusinessState(),
                    stateTable.getBusinessStateCode(),renting.getHandlingSuggestion(),"成功"
                    , BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }
    /**
     * 编辑（保存）（保存并申请）
     *
     * @param renting
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("renting")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  Renting renting,String judge) {
        common.common(stateTable,judge);
        Long userId = getUserId();
        //目前已申报总月数
        int sumMonth = rentingService.findMonth(userId);
        //剩余可申报月数
        int subMonth = 36 - sumMonth;
        //当前申报数 必须小于等于剩余可申报月份数
        if(renting.getNumberDeclarations() > subMonth){
            return JsonResult.failMessage("保存失败，非法数据，本次申报月数已超过剩余可申报数！");
        }
        renting.setDateReporting(stateTable.getDate());
        renting.setBusinessState(stateTable.getBusinessState());
        renting.setBusinessStateCode(stateTable.getBusinessStateCode());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }



    @GetMapping(MODEL + "/view.json")
    @Function("cms.renting.query")
    @ResponseBody
    public JsonResult<Renting> queryInfo(Integer id) {
        Renting renting = rentingService.queryById( id);
        return  JsonResult.success(renting);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("renting")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        rentingService.batchDelRenting(idList);
        return new JsonResult().success();
    }

    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/renting/findenterpriseedit.html");
        Renting renting = rentingService.queryById(id);
        List<Relatives> relatives= relativesService.findAllRelativesId(id);
        view.addObject("look",true);
        view.addObject("relatives", relatives);
        view.addObject("renting", renting);
        return view;
    }



    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("renting.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/renting/acceptance.html");
        Renting renting = rentingService.queryById(id);
        List<Relatives> relatives= relativesService.findAllRelativesId(id);
        view.addObject("relatives", relatives);
        view.addObject("renting", renting);
        return view;
    }


    /**
     * 受理终止
     */
    @PostMapping(MODEL + "/Admissibility.json")
    @Function("renting.company")
    @ResponseBody
    public JsonResult<String> Admissibility(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("renting"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        renting.setBusinessState(ProcessConstant.TERMINIATE_STR);
        renting.setBusinessStateCode(ProcessConstant.TERMINIATE);
        renting.setProcessResult(ProcessConstant.COMPANY_TERMINIATE_STR);

        boolean postResult = pretrialService.post(AppInterfaceType.RENTING_TYPE, renting.getExternalTaskId(), "2", "", "", renting.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = rentingService.updateTemplate(renting);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(renting.getId(), renting.getBusinessState(),
                        renting.getBusinessStateCode(), renting.getHandlingSuggestion(), ProcessConstant.COMPANY_TERMINIATE_STR, BusinessTypeConstant.renting);

                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     * 初审终止
     */
    @PostMapping(MODEL + "/FirstTrialTermination.json")
    @Function("renting.check")
    @ResponseBody
    public JsonResult<String> FirstTrialTermination(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        renting.setBusinessState(ProcessConstant.TERMINIATE_STR);
        renting.setBusinessStateCode(ProcessConstant.TERMINIATE);
        renting.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setProcessUserId(currentUser.getId().intValue());
        renting.setProcessUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),renting.getBusinessState(),
                    renting.getBusinessStateCode(),renting.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_TERMINIATE_STR,BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }

    }

    /**
     * 复审终止
     */
    @PostMapping(MODEL + "/RetrialTermination.json")
    @Function("renting.review")
    @ResponseBody
    public JsonResult<String> RetrialTermination(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        renting.setBusinessState(ProcessConstant.TERMINIATE_STR);
        renting.setBusinessStateCode(ProcessConstant.TERMINIATE);
        renting.setProcessResult(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setReviewUserId(currentUser.getId().intValue());
        renting.setReviewUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),renting.getBusinessState(),
                    renting.getBusinessStateCode(),renting.getHandlingSuggestion(),ProcessConstant.FINALCHECK_TERMINIATE_STR,BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 受理退回
     */
    @PostMapping(MODEL + "/AdmissibleReturn.json")
    @Function("renting.company")
    @ResponseBody
    public JsonResult<String> AdmissibleReturn(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("renting"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        renting.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        renting.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        renting.setProcessResult(ProcessConstant.COMPANY_BACK_STR);

        boolean postResult = pretrialService.post(AppInterfaceType.RENTING_TYPE, renting.getExternalTaskId(), "1", "", "", renting.getHandlingSuggestion(), "1");

        if (postResult) {
            boolean success = rentingService.updateTemplate(renting);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(renting.getId(), ProcessConstant.COMPANY_BACK_STR,
                        ProcessConstant.COMPANY_BACK, renting.getHandlingSuggestion(), ProcessConstant.COMPANY_BACK_STR, BusinessTypeConstant.renting);


                //给企业发一条退回信息
                Message message = new Message();
                message.setCompanyId(renting.getCompanyId());
                message.setUserId(renting.getUserId());
                message.setStatus(-1);
                message.setContent(renting.getHandlingSuggestion());
                message.setType(Integer.parseInt(BusinessTypeConstant.renting));
                message.setCreateDate(new Date());
                messageService.save(message);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }


    }

    /**
     * 初审退回
     */
    @PostMapping(MODEL + "/initialReview.json")
    @Function("renting.check")
    @ResponseBody
    public JsonResult<String> initialReview(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        renting.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        renting.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        renting.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setProcessUserId(currentUser.getId().intValue());
        renting.setProcessUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),ProcessConstant.FIRSTCHECK_STR,
                    ProcessConstant.FIRSTCHECK,renting.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_STR,BusinessTypeConstant.renting);
            //给企业发一条退回信息
            Message message=new Message();
            message.setCompanyId(renting.getCompanyId());
            message.setUserId(renting.getUserId());
            message.setStatus(-1);
            message.setContent(renting.getHandlingSuggestion());
            message.setType(Integer.parseInt(BusinessTypeConstant.renting));
            message.setCreateDate(new Date());
            messageService.save(message);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审退回
     */
    @PostMapping(MODEL + "/Reexamination.json")
    @Function("renting.review")
    @ResponseBody
    public JsonResult<String> Reexamination(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        renting.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        renting.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        renting.setProcessResult(ProcessConstant.FINALCHECK_BACK_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setReviewUserId(currentUser.getId().intValue());
        renting.setReviewUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),ProcessConstant.FINALCHECK_BACK_STR,
                    ProcessConstant.FINALCHECK_BACK,renting.getHandlingSuggestion(),ProcessConstant.FINALCHECK_BACK_STR,BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 受理通过
     */
    @PostMapping(MODEL + "/AcceptanceOK.json")
    @Function("renting.company")
    @ResponseBody
    public JsonResult<String> AcceptanceOK(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        //业务受理时间验证
        if(declareLimitService.isInTime(CommonController.getIntType("renting"),new Date())==0){
            return JsonResult.failMessage("不在业务受理时限，不可处理！");
        }
        renting.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        renting.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        renting.setProcessResult(ProcessConstant.COMPANY_ADOPT_STR);
        renting.setCompanyDeclareTime(new Date());

        boolean postResult = pretrialService.post(AppInterfaceType.RENTING_TYPE, renting.getExternalTaskId(), "0", renting.getTotalAmount().toString(), "元", renting.getHandlingSuggestion(), "0");

        if (postResult) {
            boolean success = rentingService.updateTemplate(renting);
            if (success) {
                //调用增加业务流程数据
                businessProcessService.processInformation(renting.getId(), ProcessConstant.COMPANY_ADOPT_STR,
                        ProcessConstant.COMPANY_ADOPT, renting.getHandlingSuggestion(), ProcessConstant.COMPANY_ADOPT_STR, BusinessTypeConstant.renting);
                return new JsonResult().success();
            } else {
                return JsonResult.failMessage("保存失败");
            }
        } else {
            return JsonResult.failMessage("提供人社预审处理结果接口调用异常");

        }

    }

    /**
     *  初审通过
     */
    @PostMapping(MODEL + "/FirstTrial.json")
    @Function("renting.check")
    @ResponseBody
    public JsonResult<String> FirstTrial(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        String businessType = "6";
        if (renting.getRoleName().equals("chushen")) {
            List<Sincerity> sincerityList = sincerityService.blacklist(renting.getUserId(), renting.getCompanyId(), businessType);
            if (null != sincerityList && sincerityList.size() > 0) {
                //用户或用户所属企业已进入黑名单
                for (Sincerity sincerity : sincerityList) {
                    if (sincerity.getType().equals(Long.toString(RoleConstant.PERSON))) {
                        //个人
                        return JsonResult.failMessage(renting.getName() + "在黑名单中有记录");
                    } else if (sincerity.getType().equals(Long.toString(RoleConstant.COMPANY))) {
                        //企业
                        String name = enterpriseService.findenterprise(renting.getCompanyId()).getEnterpriseName();
                        return JsonResult.failMessage(name + "公司在黑名单中有记录");
                    }
                }
            }
        }
        renting.setBusinessState(ProcessConstant.TO_FINALCHECK_STR);
        renting.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
        renting.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        //初审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setProcessUserId(currentUser.getId().intValue());
        renting.setProcessUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),ProcessConstant.FIRSTCHECK_ADOPT_STR,
                    ProcessConstant.FIRSTCHECK_ADOPT,renting.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_ADOPT_STR,BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审通过
     */
    @PostMapping(MODEL + "/ReviewThrough.json")
    @Function("renting.review")
    @ResponseBody
    public JsonResult<String> ReviewThrough(@Validated(ValidateConfig.UPDATE.class) Renting renting) {
        renting.setBusinessState(ProcessConstant.DONE_STR);
        renting.setBusinessStateCode(ProcessConstant.DONE);
        renting.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
        //复审人和id
        CoreUser currentUser = platformService.getCurrentUser();
        renting.setReviewUserId(currentUser.getId().intValue());
        renting.setReviewUserName(currentUser.getName());
        boolean success = rentingService.updateTemplate(renting);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(renting.getId(),ProcessConstant.FINALCHECK_ADOPT_STR,
                    ProcessConstant.FINALCHECK_ADOPT,renting.getHandlingSuggestion(),ProcessConstant.FINALCHECK_ADOPT_STR,BusinessTypeConstant.renting);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @PostMapping(MODEL + "/batchFinalCheckPass.json")
    @Function("renting.review")
    @ResponseBody
    public JsonResult<String> batchFinalCheckPass(String ids,String year) {
        /**
         * 更改状态为生效
         */
        List<Long> idList = ConvertUtil.str2longs(ids);
        for(Long id : idList){
            /**
             * 获得这个公司id下所有待复审的业务
             */
            RentingQuery condtion = new RentingQuery();

            if (StringUtils.isEmpty(year)) {
                Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
                year = yearNum.toString();
            }
            condtion.setYear(year.trim());
            condtion.setCompanyId(String.valueOf(id));

            List<String> params = new ArrayList();
            params.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
            condtion.setIds(params);
            PageQuery page = condtion.getPageQuery();
            page.setPageSize(Integer.MAX_VALUE);
            rentingService.queryEmployees(page);
            List<Renting> rentingList = page.getList();

            for(Renting renting : rentingList){
                renting.setBusinessState(ProcessConstant.DONE_STR);
                renting.setBusinessStateCode(ProcessConstant.DONE);
                renting.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
                //复审人和id
                CoreUser currentUser = platformService.getCurrentUser();
                renting.setReviewUserId(currentUser.getId().intValue());
                renting.setReviewUserName(currentUser.getName());
                boolean success = rentingService.updateTemplate(renting);
                if (success) {
                    //调用增加业务流程数据
                    businessProcessService.processInformation(renting.getId(),ProcessConstant.FINALCHECK_ADOPT_STR,
                            ProcessConstant.FINALCHECK_ADOPT,renting.getHandlingSuggestion(),ProcessConstant.FINALCHECK_ADOPT_STR,BusinessTypeConstant.renting);
                } else {
                    return JsonResult.failMessage("保存失败");
                }
            }
        }
        return JsonResult.success();
    }




    //跳转修改配偶、未成年子女信息信息页面
    @GetMapping(MODEL + "/addRelatives.do")
    @Function("renting")
    @ResponseBody
    public ModelAndView addRelatives(Integer id) {
        ModelAndView view = new ModelAndView("/cms/renting/relativesAdd.html");
        view.addObject("id",id);
        Relatives relatives=relativesService.findRelativesId(id);
        view.addObject("relatives", relatives);
        return view;
    }

    //跳转新增配偶、未成年子女信息信息页面
    @GetMapping(MODEL + "/editRelatives.do")
    @Function("renting")
    @ResponseBody
    public ModelAndView editRelatives(Integer id) {
        ModelAndView view = new ModelAndView("/cms/renting/relativesEdit.html");
        Relatives relatives=relativesService.findRelativesId(id);
        view.addObject("relatives", relatives);
        return view;
    }

    //修改配偶、未成年子女信息信息
    @PostMapping(MODEL + "/editRelatives.json")
    @Function("renting")
    @ResponseBody
    public JsonResult<String> editRelatives(@Validated(ValidateConfig.UPDATE.class)  Relatives relative) {
        boolean success = relativesService.updateTemplate(relative);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    //新增配偶、未成年子女信息信息
    @PostMapping(MODEL + "/addRelatives.json")
    @Function("renting")
    @ResponseBody
    public JsonResult addRelatives(@Validated(ValidateConfig.ADD.class)Relatives relative) {
        boolean success = relativesService.save(relative);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    //根据ID删除亲属信息
    @PostMapping(MODEL + "/deleteRelatives.json")
    @Function("renting")
    @ResponseBody
    public JsonResult deleteRelatives(String id) {
        relativesService.deleteRelatives(Integer.parseInt(id));
        return new JsonResult().success();
    }



// 人才公共方法(所有)

    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }

    /**
     * 获取初审的数量 type = 'TODO'
     */
    private int firstCheckNumber(Long companyId, String type,String year) {

        RentingQuery condition = new RentingQuery();
        condition.setCompanyId(String.valueOf(companyId));

        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        } else {
        ids.add(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        ids.add(ProcessConstant.FIRSTCHECK_STR);
        ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        ids.add(ProcessConstant.COMPANY_ADOPT_STR);
        ids.add(ProcessConstant.FINALCHECK_BACK_STR);
        }

        condition.setIds(ids);
        int size = rentingService.queryEmployeesCount(condition);
        return size;
    }

    /**
     * 获取复审的数量  待复审 - type = 'TODO'
     */
    private int finalCheckNumber(Long companyId, String type,String year) {
        /**
         * 获取待初审的数量,
         */
        RentingQuery condition = new RentingQuery();
        if(StringUtils.isEmpty(year)){
            Integer yearNum = Calendar.getInstance().get(Calendar.YEAR);
            year = yearNum.toString();
        }
        condition.setYear(year);
        condition.setCompanyId(String.valueOf(companyId));

        List<String> ids = new ArrayList();
        if ("TODO".equalsIgnoreCase(type)) {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        } else {
            ids.add(ProcessConstant.FIRSTCHECK_ADOPT_STR);

            ids.add(ProcessConstant.FINALCHECK_TERMINIATE_STR);
            ids.add(ProcessConstant.FINALCHECK_BACK_STR);
            ids.add(ProcessConstant.FINALCHECK_ADOPT_STR);
        }

        condition.setIds(ids);
        int size = rentingService.queryEmployeesCount(condition);
        return size;
    }
}
